package com.example.mybatis.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.validation.ConstraintViolation;
import java.util.Set;

/**
 * Hibernate Validator 校验信息解析为通用格式
 *
 * @author wangji
 * @date 2019/4/3 4:18 PM
 */
@Slf4j
public class ConstraintViolationUtils {

    /**
     * 校验没有问题 返回 new ActionResult<>(true)，否则返回 new ActionResult<>(false);
     *
     * @param constraintViolations
     * @return
     */
    public static R validatorConstraintViolations(Set<? extends ConstraintViolation<?>> constraintViolations) {
        if (constraintViolations == null || constraintViolations.isEmpty()) {
            return R.ok("");
        }
        for (ConstraintViolation item : constraintViolations) {
            log.info("validator error:" + item.getPropertyPath().toString() + "  message:" + item.getMessage());
            return parseMessageAndCodeFromValidatorError(item.getMessage());
        }
        return R.error("参数有误");

    }

    /**
     * 状态码分隔符
     */
    public static final String STATE_CODE_DIVIDER = "#";

    /**
     * 从校验信息中解析meesage and code；eg：message = "参数错误 #202"
     *
     * @param message
     */
    public static R parseMessageAndCodeFromValidatorError(String message) {
        if (message.indexOf(STATE_CODE_DIVIDER) > 0) {
            String[] messages = message.split(STATE_CODE_DIVIDER);
            return R.error(Integer.parseInt(messages[1]), messages[0]);
        }
        return R.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
    }

}
